import React, { Component, Fragment } from 'react';
import StandardTable from '@/components/StandardTable';
import { Icon, Form, Input, Modal, Select, Row, Col, Upload, DatePicker } from 'antd';
import AntdDatePicker from '@/components/AntdDatePicker';
import { connect } from 'dva';
import styles from '@/pages/Info.less';
import moment from 'moment';
import AdSelect from '@/components/AdSelect';
import AntdUpload from '@/components/AntdUpload';
import prompt from '@/components/Prompt';
import AdButton from '@/components/AdButton';
const { RangePicker } = DatePicker;
import { codes, renderTableAdSelect } from './utils';
import { papersStatus, allDictList } from '@/utils/constans';
import {
  queryDictData,
  formatFile,
  queryFileList,
  filterAddFile,
  filterDeteteFile,
  queryDict,
} from '@/utils/common';
import FileReader from '@/components/FileReader';
const { TextArea } = Input;
const { Option } = Select;
const dateFormat = 'YYYY-MM-DD';

@connect(({ tmsDriver, loading, component }) => ({
  tmsDriver,
  loading: loading.effects['tmsDriver/selectDetails'],
  dictObject: component.dictObject,
}))
@Form.create()
export default class parperInfo extends Component {
  state = {
    id: 0,
    fileList: [],
    deleteFileIds: [],
    previewVisible: false,
    previewImage: '',
    detailId: '',
    imageList: [],
    index: 0,
  };
  fileList = [];

  componentDidMount() {}
  componentWillMount() {
    const allDict = [allDictList.papersType];
    queryDict({ props: this.props, allDict });
  }

  columns = [
    {
      title: '证件类型',
      dataIndex: 'type',
      render: (text, record) => this.renderType(text, record),
      fixed: this.props.isMobile ? false : true,
      width: this.props.isMobile ? 'auto' : 150,
    },
    {
      title: '证件号码',
      dataIndex: 'cardCode',
    },
    {
      title: '有效期',
      dataIndex: 'expiryStartTime',
      width: 150,
      render: (text, record) => (
        <span>
          {record.expiryStartTime}~{record.expiryEndTime}
        </span>
      ),
    },
    {
      title: '备注',
      dataIndex: 'remarks',
    },
    {
      title: '状态',
      dataIndex: 'papersStatus',
      render: text => renderTableAdSelect({ props: this.props, value: text, data: papersStatus }),
    },
    {
      title: '附件',
      dataIndex: 'attaQuantity',
      render: (text, record) => (
        <FileReader
          type="list"
          count={text}
          urlType="tms"
          params={{ bizId: record.id, fileBizType: 'DRIVER_PAPERS' }}
        />
      ),
    },
  ];
  renderType = (text, record) => {
    const content = renderTableAdSelect({
      props: this.props,
      value: text,
      key: allDictList.papersType,
    });
    return content;
    // return type === 'list' ? (
    //   <AdButton
    //     mode={'a'}
    //     onClick={e => this.showDetail(e, 'edit', record.id)}
    //     text={content}
    //     code={codes.editPaper}
    //   />
    // ) : (
    //   content
    // );
  };

  queryFileList = id => {
    queryFileList({
      props: this.props,
      params: { bizId: id, fileBizType: 'DRIVER_PAPERS' },
      callback: data => {
        if (!data) return;
        this.fileList = data;
        this.props.form.setFieldsValue({ fileTokens: data });
      },
    });
  };

  // 显示详情
  showDetail = (e, type, id) => {
    const { showDetail, dispatch } = this.props;
    this.queryFileList(id);
    dispatch({
      type: 'tmsDriver/selectPapersDetails',
      payload: { id },
      callback: data => {
        this.setFileList(data.attachments);
      },
    });

    this.setState({ detailId: id });
    if (showDetail) showDetail(e, type, id);
  };

  // 设置图片
  setFileList = list => {
    this.setState({ fileList: list });
  };

  // 上传图片
  handleChange = fileList => {
    this.setState({ fileList });
  };

  // 删除图片
  onRemove = deleteFileIds => {
    this.setState({
      deleteFileIds,
    });
  };

  //确认新增证件：
  handleOk = e => {
    const { deleteFileIds, fileList, detailId } = this.state;
    const { id, titleType, form, dispatch } = this.props;
    form.validateFieldsAndScroll((err, values) => {
      if (err) {
        return;
      }
      const { expiryTime, fileTokens, ...value } = values;
      value.expiryStartTime = expiryTime ? moment(expiryTime[0]).format(dateFormat) : '';
      value.expiryEndTime = expiryTime ? moment(expiryTime[1]).format(dateFormat) : '';
      //图片：

      value.fileTokens = filterAddFile(fileTokens);
      if (titleType == 'add') {
        //新增时传入司机id:
        value.driverId = id;
      } else {
        //编辑时传入证件id:
        value.id = detailId;
        value.deleteFileIds = filterDeteteFile(fileTokens, this.fileList);
      }
      dispatch({
        type: 'tmsDriver/paperOperate',
        payload: value,
        callback: data => {
          this.handleCancel();
          dispatch({
            type: 'tmsDriver/selectDetails',
            payload: { id },
          });
        },
      });
    });
  };

  handleCancel = () => {
    const { handleCancel, form } = this.props;
    handleCancel();
    form.resetFields();
  };

  render() {
    const {
      loading,
      data,
      visible,
      handleCancel,
      form: { getFieldDecorator },
      id,
      type,
      tmsDriver: { detailsPaper },
      // component: { dictObject },
      dictObject,
      titleType,
    } = this.props;
    const { previewVisible, previewImage, fileList } = this.state;
    const details = titleType == 'add' ? {} : detailsPaper;
    return (
      <Fragment>
        <StandardTable
          loading={loading}
          data={data}
          disabledRowSelected={true}
          scrollX={800}
          scrollY={200}
          columns={this.columns}
          // onPaginationChange={change}
        />
        {visible && (
          <Modal
            title={titleType == 'add' ? '新增证件' : '编辑证件'}
            visible={visible}
            onOk={this.handleOk}
            onCancel={this.handleCancel}
            width={620}
            destroyOnClose={true}
            style={{ top: 20 }}
          >
            <div className={styles.tableListForm}>
              <Form layout="inline">
                <Row gutter={{ md: 4, lg: 12, xl: 24 }}>
                  <Col md={{ span: 12 }} sm={24}>
                    <Form.Item label="证件类型">
                      {getFieldDecorator('type', {
                        rules: [{ required: true, message: '请输入证件类型' }],
                        initialValue: details.type ? details.type : undefined,
                      })(
                        <Select placeholder="请选择">
                          {dictObject['papers-type'] &&
                            dictObject['papers-type'].map(item => (
                              <Option key={item.code}>{item.value}</Option>
                            ))}
                        </Select>
                      )}
                    </Form.Item>
                  </Col>
                  <Col md={{ span: 12 }} sm={24}>
                    <Form.Item label="证件号码">
                      {getFieldDecorator('cardCode', {
                        rules: [{ required: true, message: '请输入证件号码' }],
                        initialValue: details.cardCode,
                      })(<Input placeholder="请输入证件号码" />)}
                    </Form.Item>
                  </Col>
                </Row>
                <Row>
                  <Col span={24}>
                    <Form.Item label="有效期" wrapperCol={{ span: 18 }} labelCol={{ span: 4 }}>
                      {getFieldDecorator('expiryTime', {
                        rules: [{ required: true, message: '请输入有效期' }],
                        initialValue: details.expiryStartTime
                          ? [
                              moment(details.expiryStartTime, dateFormat),
                              moment(details.expiryEndTime, dateFormat),
                            ]
                          : '',
                      })(<AntdDatePicker mode="range" />)}
                    </Form.Item>
                  </Col>
                </Row>
                <Row>
                  <Col span={24}>
                    <Form.Item label="备注" wrapperCol={{ span: 18 }} labelCol={{ span: 4 }}>
                      {getFieldDecorator('remarks', { initialValue: details.remarks })(
                        <TextArea rows={4} />
                      )}
                    </Form.Item>
                  </Col>
                </Row>
                <Row>
                  <Col span={24}>
                    <Form.Item label="图片">
                      {getFieldDecorator('fileTokens')(<FileReader urlType="tms" />)}
                    </Form.Item>
                  </Col>
                </Row>
              </Form>
            </div>
          </Modal>
        )}
      </Fragment>
    );
  }
}
